package com.chenyun.boot.datasource.config;

import com.alibaba.druid.util.Utils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.chenyun.boot.datasource.extension.EasySqlInjector;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 配置主类
 *
 * @author Lonni
 * @date 2022-06-08 20:07
 */
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
//指定扫描
@MapperScan(value = {"com.chenyun.**.mapper", "com.lonni.**.mapper"})
public class DataSourceConfig {


    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加非法SQL拦截器
//        interceptor.addInnerInterceptor(new IllegalSQLInnerInterceptor());
        //全表更新和删除插件
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        //乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
    /**
     * 批量执行sql
     *
     * @return
     */
    @Bean
    public EasySqlInjector customSqlInjector() {
        return new EasySqlInjector();
    }


    /**
     * 去除druid底部广告
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean removeDruidAdFilter() throws IOException {
        // 获取common.js内容
        String text = Utils.readFromResource("support/http/resources/js/common.js");
        // 屏蔽 this.buildFooter(); 直接替换为空字符串,让js没机会调用
        final String newJs = text.replace("this.buildFooter();", "");
        // 新建一个过滤器注册器对象
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        // 注册common.js文件的过滤器
        registration.addUrlPatterns("/druid/js/common.js");
        // 添加一个匿名的过滤器对象,并把改造过的common.js文件内容写入到浏览器
        registration.setFilter(new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
                // 重置缓冲区，响应头不会被重置
                response.resetBuffer();
                // 把改造过的common.js文件内容写入到浏览器
                response.getWriter().write(newJs);
            }
        });
        return registration;

    }


}
